package com.baomidou.ant.weChat.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.ant.weChat.model.AccessToken;
import com.baomidou.ant.weChat.util.RestUtils;
import lombok.extern.log4j.Log4j2;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author zhoubb@fpe.com.cn
 * 推送企业微信配置(推送token方法)
 * */
@Log4j2
public class WxConfig {
    //企业应用密钥--推送消息应用的密钥
    private static final String secret="sVJAm66-Ye3FMyVtX0gJU6FRwaYdSQ4JPkRSMs-JQN4";
    //企业id
    private static final String corpId="wweb11f3ce9a2cf27f";
    //企业微信配置url--获取token的URL
    private static final String tokenUrl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + secret;

    /**
     * 方法1:获取应用access_token
     *  每个应用有独立的secret，获取到的access_token只能本应用使用，所以每个应用的access_token应该分开来获取
     *  开发者需要缓存access_token，用于后续接口的调用（注意：不能频繁调用gettoken接口，否则会受到频率拦截）。当access_token失效或过期时，需要重新获取。
     * @return String
     */
    public static String getAccessTokenOne(){
        String result = "";
        Map response = RestUtils.get(tokenUrl);
        //token返回
        if (response.containsKey("errcode") && (Integer) response.get("errcode") != 0) {
            //获取错误日志
            log.error(response.toString());
        } else {
            result = (String) response.get("access_token");
        }
        return result;
    }

    /**
     * 方法2：获取应用access_token
     * @return
     */
    public static AccessToken getAccessTokenTwo() {
        AccessToken token = new AccessToken();
        //访问微信服务器
        try {
            URL getUrl = new URL(tokenUrl);
            //开启连接，并返回一个URLConnection对象
            HttpURLConnection http = (HttpURLConnection)getUrl.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            //将URL连接用于输入和输出，一般输入默认为true，输出默认为false
            http.setDoOutput(true);
            http.setDoInput(true);
            //进行连接，不返回对象
            http.connect();
            //获得输入内容,并将其存储在缓存区
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            //将内容转化为JSON代码
            String message = new String(buffer, StandardCharsets.UTF_8);
            JSONObject json = JSONObject.parseObject(message);
            //提取内容，放入对象
            token.setAccess_token(json.getString("access_token"));
            token.setExpires_in(new Integer(json.getString("expires_in")));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回access_token码
        return token;
    }

}
